package com.xingchi.tornado.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xingchi.tornado.basic.Result;
import com.xingchi.tornado.core.code.SecurityCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证异常处理器
 *
 * @author xingchi
 * @date 2024/11/28 22:25
 */
@Slf4j
public class ExceptionAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ObjectMapper objectMapper;

    public ExceptionAuthenticationEntryPoint(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        log.info("用户访问失败：{}", authException.getMessage(), authException);
        Result<String> fail = Result.fail(SecurityCode.UNAUTHORIZED, "请登录后重试");
        response.getWriter().print(objectMapper.writeValueAsString(fail));
    }
}
